﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Data.Common;
using System.Data;
using System.Globalization;
using ResourceBlender.DAL;
using ResourceBlender.Core;

namespace ResourceBlender.Express {
    /// <summary>
    /// Allows duplication of all translations from one language to another.
    /// </summary>
    public partial class WinCreateVariant : Window {
        private bool success = false;
        /// <summary>
        /// Gets whether the translation was completed successfully.
        /// </summary>
        /// <value><c>true</c> if successful; otherwise, <c>false</c>.</value>
        public bool Success { get { return success; } }

        /// <summary>
        /// Initializes a new <see cref="WinCreateVariant"/>.
        /// </summary>
        public WinCreateVariant() {
            InitializeComponent();
        }

        /// <summary>
        /// Loads the list of unique languages when the window loads.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void Window_Loaded(object sender, RoutedEventArgs e) {
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (s, dwe) => {
                dwe.Result = ResourceBlenderDAL.GetUniqueLanguages();
            };
            worker.RunWorkerCompleted += (s, rwe) => {
                SetStatus(null, false);
                if(rwe.Error != null) {
                    DialogBox.Show(this, rwe.Error.Message, "Error", DialogBox.DialogBoxType.OK, DialogBox.DialogBoxIcon.Error);
                } else {
                    var langs = rwe.Result as IEnumerable<KeyValuePair<string, CultureInfo>>;
                    ObservableSortedDictionary<string, CultureInfo> uniqueLangs = new ObservableSortedDictionary<string, CultureInfo>(new Comparers.CultureInfoEnglshNameComparer(), new Comparers.StringEqualityComparer());
                    foreach(var lang in langs) {
                        uniqueLangs.Add(lang.Key, lang.Value);
                    }
                    if(langs != null) {
                        if(uniqueLangs.Count > 0) {
                            lstSourceLanguage.ItemsSource = uniqueLangs;
                        } else {
                            DialogBox.Show(this, "No resources exist. Before creating a language variant, at least one resource must be added.", "Error", DialogBox.DialogBoxType.OK, DialogBox.DialogBoxIcon.Error);
                            Close();
                        }
                    }
                }
            };
            SetStatus("Loading languages...", true);
            worker.RunWorkerAsync();
            ObservableSortedDictionary<string, CultureInfo> availableLangs = new ObservableSortedDictionary<string, CultureInfo>(new Comparers.CultureInfoEnglshNameComparer());
            foreach(CultureInfo culture in CultureInfo.GetCultures(CultureTypes.AllCultures)) {
                if(culture.Name == "") {
                    continue;
                }
                availableLangs.Add(culture.Name, culture);
            }
            lstDestinationLanguage.ItemsSource = availableLangs;
        }

        /// <summary>
        /// Starts copying between languages.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.ExecutedRoutedEventArgs"/> instance containing the event data.</param>
        private void CreateVariant(object sender, ExecutedRoutedEventArgs e) {
            if(ValidateSelection()) {
                string sourceLanguage = lstSourceLanguage.SelectedValue.ToString(), 
                       destinationLanguage = lstDestinationLanguage.SelectedValue.ToString();
                bool overwriteExisting = radOverwrite.IsChecked == true;
                BackgroundWorker worker = new BackgroundWorker();
                worker.WorkerReportsProgress = true;
                worker.WorkerSupportsCancellation = true;
                worker.DoWork += (s, dwe) => {
                    StatusMessage.StatusChangedEventHandler logHandler = new StatusMessage.StatusChangedEventHandler(message => {
                        worker.ReportProgress(0, message);
                    });
                    ResourceBlenderDAL.CreateVariant(sourceLanguage, destinationLanguage, overwriteExisting, worker, logHandler);
                };
                WinWorkerLog dlg = new WinWorkerLog("Copying translations...", worker);
                dlg.Owner = this;
                dlg.ShowDialog();
                if(dlg.Success) {
                    this.success = true;
                    Close();
                }
            }
        }

        

        /// <summary>
        /// Validates the selection is valid.
        /// </summary>
        /// <returns></returns>
        private bool ValidateSelection() {
            bool valid = true;
            if(lstSourceLanguage.SelectedValue == null) {
                DialogBox.ShowAlert(this, "Source language must be specified", "Error");
                valid = false;
            } else if(lstDestinationLanguage.SelectedValue == null) {
                DialogBox.ShowAlert(this, "Destination language must be specified", "Error");
                valid = false;
            } else if(lstSourceLanguage.SelectedValue == lstDestinationLanguage.SelectedValue) {
                DialogBox.ShowAlert(this, "Source and destination languages must be different", "Error");
                valid = false;
            }
            return valid;
        }

        /// <summary>
        /// Shows the help file.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.ExecutedRoutedEventArgs"/> instance containing the event data.</param>
        private void ShowHelp(object sender, ExecutedRoutedEventArgs e) {
            WPFUtils.OpenHelp("Creating.Variants.html");
        }

        /// <summary>
        /// Sets the text on the status message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="showProgress"><c>true</c> if the progress bar should be shown, otherwise <c>false</c>.</param>
        private void SetStatus(string message, bool showProgress) {
            prgStatus.Visibility = showProgress ? Visibility.Visible : Visibility.Hidden;
            if(message == null) {
                lblStatus.Visibility = Visibility.Hidden;
            } else {
                lblStatus.Visibility = Visibility.Visible;
                lblStatus.Content = message;
            }
        }

        /// <summary>
        /// Closes the window.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.ExecutedRoutedEventArgs"/> instance containing the event data.</param>
        private void CloseWindow(object sender, ExecutedRoutedEventArgs e) {
            Close();
        }
    }
}
